//
//  ResetPhoneViewController.m
//  YCVillageDoctor
//
//  Created by Mac on 2017/6/8.
//  Copyright © 2017年 zhangxiaoliang. All rights reserved.
//

#import "ResetPhoneViewController.h"
#import "YCTabbarViewController.h"
#import "YCSSKeychain.h"
@interface ResetPhoneViewController ()
{
    int  _timeTick;
}
@property (weak, nonatomic) IBOutlet UIImageView *topImageView;

@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
@property (weak, nonatomic) IBOutlet UIButton *getCodeBtn;
@property (weak, nonatomic) IBOutlet UIView *codeView;
@property (weak, nonatomic) IBOutlet UIButton *validateCodeBtn;
@property (weak, nonatomic) IBOutlet UIView *notiView;
@property (weak, nonatomic) IBOutlet UILabel *codeLabel;
//短息语音切换的参数
@property (nonatomic ,strong)NSString *codeType;

//是否短信和语音切换
@property (nonatomic,assign)BOOL  swithType;
//时间
@property (strong ,nonatomic)NSTimer *timer;

@end

@implementation ResetPhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //语音短信切换初始化
    self.codeType =@"0";
    self.swithType = NO;
    _getCodeBtn.backgroundColor = [UIColor whiteColor];
    _getCodeBtn.layer.masksToBounds = YES;
    _getCodeBtn.layer.cornerRadius = 3;
    _getCodeBtn.layer.borderWidth = 0.5;
    _getCodeBtn.layer.borderColor = GreenColor.CGColor;
    [_getCodeBtn setTitleColor:GreenColor forState:UIControlStateNormal];
    
    _validateCodeBtn.backgroundColor = GreenColor;
    _validateCodeBtn.layer.masksToBounds = YES;
    _validateCodeBtn.layer.cornerRadius = 6;
    
    [_getCodeBtn addTarget:self action:@selector(codeBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    
    self.notiView.hidden = YES;
    self.notiView.userInteractionEnabled = YES;
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideCodeView)];
    [self.notiView addGestureRecognizer:tap];
    
    [UITextField setupColorWith:@[self.codeTextField]];
    // Do any additional setup after loading the view from its nib.
    
    
    
    _topImageView.layer.cornerRadius = 10;
    _topImageView.layer.masksToBounds = YES;
    
    
    
    
}
#pragma mark - hideCodeView
- (void)hideCodeView{
    self.notiView.hidden = YES;
}

#pragma mark - 辞去第一响应者
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}




#pragma mark - 返回按钮
- (IBAction)backAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 获取验证码
- (void)codeBtnClicked {
    [self validationWithCode];
    _timeTick = 61;
    self.timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
    _getCodeBtn.enabled = NO;
}

#pragma mark 获取验证码，60秒倒计时
-(void)timeFireMethod{
    _timeTick--;
    if(_timeTick==0){
        [self.timer invalidate];
        self.getCodeBtn.enabled = YES;
        if (!self.swithType) {
            
            self.codeType = @"1";
            self.swithType =YES;
            
            
            [self.getCodeBtn setTitle:@"语音验证码" forState:UIControlStateNormal];
            
            
        }else{
            self.codeType = @"0";
            
            self.swithType =NO;
            
            [self.getCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        }
        
    }else
    {
        NSString *str = [NSString stringWithFormat:@"%d秒",_timeTick];
        [self.getCodeBtn setTitle:str forState:UIControlStateNormal];
        if (_timeTick ==0) {
            [self.timer invalidate];
            self.getCodeBtn.enabled = YES;
            
            if (!self.swithType) {
                
                self.codeType = @"1";
                self.swithType =YES;
                
                [self.getCodeBtn setTitle:@"语音验证码" forState:UIControlStateNormal];
                
                
            }else{
                self.codeType = @"0";
                self.swithType =NO;
                
                
                [self.getCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            }
        }
        
    }
}
/**
 *  网络验证code
 */
-(void)validationWithCode{
     __weak typeof(self)WeakSekf = self;
    
    NSString *url = kGetNewCode;
    NSDictionary *params =@{
                            @"link_phone":_phone,
                            @"sms_type":self.codeType,
                            @"client_id":@"14",
                            @"post_ip":@"192.168.141.219"
                            };
    [DownloadData post:url params:params success:^(id json) {
        
        if (![[json allKeys] containsObject:@"error_code"]){
            [WeakSekf presentSuccessTips:@"已发送！"];
            NSLog(@"验证码是:%@",json[@"phone_code"]);
        }else{
            [WeakSekf presentFailureTips:@"验证码发送失败！"];
        }
    } failure:^(NSError *error) {
        
    }];
    
    
}

#pragma mark － 判断网络验证code
- (IBAction)validateBtnClicked{

    if ([_codeTextField.text isEqualToString:@""]) {

    [self presentMessageTips:@"请输入验证码！"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self dismissTips];
    });
    return;
    }
     [[UIApplication sharedApplication].keyWindow  presentLoadingTips:nil];
 __weak typeof(self)WeakSekf = self;
    NSString *url = kResetCode;
    NSDictionary *params =@{
                            @"link_phone":self.phone,
                            @"phone_code":_codeTextField.text
                            };
    
    [DownloadData post:url params:params success:^(id json) {
        
        [[UIApplication sharedApplication].keyWindow  dismissTips];
        
        if([json[@"error_code"] isEqualToString:@"00014"])
        {
            
            [[UIApplication sharedApplication].keyWindow  presentSuccessTips:@"验证码错误,请重新输入"];
            
            return ;
            
        }
        
        if ([json[@"error_code"] isEqualToString:@"ok"]) {
       
            [WeakSekf.codeTextField resignFirstResponder];
            UIWindow *window= [UIApplication sharedApplication].keyWindow;
            [[UIApplication sharedApplication].keyWindow.rootViewController dismissViewControllerAnimated:NO completion:^{
                
                //保存登录手机号
                NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
                
                [def setObject:self.phone forKey:KLINKMOBILE];
                [def setObject:self.expertId forKey:KEXPERTID];
                [def setObject:self.checkFlag forKey:KCHECKFLAG];
                
                [YCUserTool sharedTools].linkMobile = (self.phone==nil?@"":self.phone);
                [YCUserTool sharedTools].expertID = (self.expertId==nil?@"":self.expertId);
                
              
                //将用户的密码保存
                BOOL ii = [YCSSKeychain saveValue:self.pwd andKey:self.phone];
                
                if (ii) {
                    NSLog(@"保存成功");
                }
                
                [def synchronize];
                YCTabbarViewController *hoVC = [[YCTabbarViewController alloc]init];
                window.rootViewController = hoVC;
                
            }];
         
        }else{
             [[UIApplication sharedApplication].keyWindow  presentSuccessTips:@"验证码错误,请重新输入"];
        }
        
    } failure:^(NSError *error) {
         [[UIApplication sharedApplication].keyWindow dismissTips];
    }];
    
}


@end
